import 'package:amap_map_fluttify/amap_map_fluttify.dart';
import 'package:decorated_flutter/decorated_flutter.dart';
import 'package:flutter/material.dart';
import 'package:fluttermarketingplus/utils/permission_request.dart';
import 'package:fluttermarketingplus/utils/next_latlng.dart';

import 'order_page/achievement_widget.dart';
import 'order_page/amount_distribution_widget.dart';

final _assetsIcon = Uri.parse('images/test_icon.png');

//订单页面
class OrderPage extends StatefulWidget {
  @override
  _OrderPageState createState() => _OrderPageState();
}

class _OrderPageState extends State<OrderPage> with NextLatLng {
  AmapController _controller;

  //点标记
  List<Marker> _markers = [];

  //画圆圈标记
  List<Circle> _circleList = [];

  @override
  Widget build(BuildContext context) {
    return MediaQuery.removePadding(
        removeTop: true,
        context: context,
        child: DecoratedColumn(
          children: <Widget>[
            Flexible(
              flex: 1,
              child: AmapView(
                mapType: MapType.Satellite,
                showZoomControl: false,
                zoomLevel: 16,
                maskDelay: Duration(milliseconds: 500),
                // 地图创建完成回调 (可选)
                onMapCreated: (controller) async {
                  _controller = controller;
                  if (await requestPermission()) {
                    MyLocationOption myLocationOption = MyLocationOption(
                      show: true,
                      myLocationType: MyLocationType.Rotate,
                      iconUri: _assetsIcon, //加载本地图片
                      imageConfiguration:
                          createLocalImageConfiguration(context),
                    );
                    await controller.showMyLocation(myLocationOption);
                  }
                },
              ),
            ),
            Flexible(
              child: DecoratedColumn(
                scrollable: true,
                divider: kDividerZero,
                children: <Widget>[
                  AchievementWidget(),
                  AmountDistributionWidget(),
                  //添加标记物
                  ListTile(
                    title: Center(child: Text('添加Marker')),
                    onTap: () async {
                      print('开始添加marker....');
                      final latLng = await _controller?.getLocation();
                      print('当前获取到的经纬度坐标为:${latLng.toString()}');
                      final marker = await _controller?.addMarker(
                        MarkerOption(
                          latLng:
                              getNextLatLng(latLng.latitude, latLng.longitude),
                          title: '北京',
                          snippet: '描述',
                          iconUri: _assetsIcon,
                          imageConfig: createLocalImageConfiguration(context),
                          width: 48,
                          height: 48,
                          object: '自定义数据',
                        ),
                      );
                      _markers.add(marker);
                    },
                  ),
                  ListTile(
                    title: Center(child: Text('添加圆')),
                    onTap: () async {
                      final latLng = await _controller?.getLocation();
                      final circle = await _controller?.addCircle(CircleOption(
                        center: LatLng(latLng.latitude, latLng.longitude),
                        radius: 200,
                        width: 10,
                        strokeColor: Colors.green,
                      ));
                      _circleList.add(circle);
                    },
                  ),
                  ListTile(
                    title: Center(child: Text('删除圆')),
                    onTap: () async {
                      if (_circleList.isNotEmpty) {
                        await _circleList.first.remove();
                        _circleList.removeAt(0);
                      }
                    },
                  ),
                  ListTile(
                    title: Center(child: Text('添加Widget Marker')),
                    onTap: () async {
                      final latLng = await _controller?.getLocation();
                      final marker = await _controller?.addMarker(
                        MarkerOption(
                          latLng: getNextLatLng(latLng.latitude, latLng.longitude),
                          widget: Column(
                            mainAxisSize: MainAxisSize.min,
                            children: <Widget>[
                              Text('使用Widget作为Marker'),
                              FlutterLogo(size: 80),
                            ],
                          ),
                          imageConfig: createLocalImageConfiguration(context),
                          title: '北京',
                          snippet: '描述',
                          width: 100,
                          height: 100,
                        ),
                      );
                      _markers.add(marker);
                    },
                  ),
                  ListTile(
                    title: Center(child: Text('调用方法开启弹窗')),
                    onTap: () async {
                      if (_markers.isNotEmpty) {
                        final marker = _markers[0];
                        marker.showInfoWindow();
                      }
                    },
                  ),
                ],
              ),
            ),
          ],
        ));
  }
}

extension on AmapController {
  Future<LatLng> getLocationX() {
    final interval = const Duration(milliseconds: 500);
    final timeout = const Duration(seconds: 10);
    return platform(
      android: (pool) async {
        final map = await androidController.getMap();
        return Stream.periodic(interval, (_) => _)
            .asyncMap(
              (count) async {
                final coord = await map.getMyLocation();

                if (coord == null) {
                  return null;
                } else {
                  return LatLng(await coord.latitude, await coord.longitude);
                }
              },
            )
            .take(timeout.inMilliseconds ~/ interval.inMilliseconds)
            .firstWhere((location) => location != null)
            .timeout(timeout, onTimeout: () => null);
      },
      ios: (pool) {
        return Stream.periodic(interval, (_) => _)
            .asyncMap(
              (count) async {
                final location = await iosController.get_userLocation();
                final coord = await location.get_coordinate();

                if (coord == null) {
                  return null;
                } else {
                  return LatLng(await coord.latitude, await coord.longitude);
                }
              },
            )
            .take(timeout.inMilliseconds ~/ interval.inMilliseconds)
            .firstWhere((location) => location != null)
            .timeout(timeout, onTimeout: () => null);
      },
    );
  }
}
